/*
 * Created on May 31, 2005
 *
 */
package com.erclab.internal.xpresso.repositories;

import java.util.*;

import com.erclab.internal.xpresso.dataAccess.*;
import com.erclab.internal.xpresso.exceptions.RepositoryException;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.log4j.Logger;


/**
 * @author Enrique Rodriguez.
 *
 */
public class MysqlRepository extends Repository {

	// Create the log for this class
	protected static final Logger log = Logger.getLogger(MysqlRepository.class);
	
	protected void loadConfiguration() throws RepositoryException {

		PropertyResourceBundle p = (PropertyResourceBundle) ResourceBundle.getBundle("com.erclab.internal.xpresso.repositories.MysqlRepository");
		convertResourceBundleToProperties(p);
		
		if (properties == null){
			log.error("The properties com.erclab.internal.xpresso.repositories.Mysqlrepository could not be found");
			throw new RepositoryException("The properties com.erclab.internal.xpresso.repositories.Mysqlrepository could not be found");
		}
	}

	protected void convertResourceBundleToProperties(PropertyResourceBundle p) {
		properties = new Properties();
		properties.setProperty("username", (String)p.handleGetObject("username"));
		properties.setProperty("password", (String)p.handleGetObject("password"));
		properties.setProperty("driverClassName", (String)p.handleGetObject("driverClassName"));
		properties.setProperty("url", (String)p.handleGetObject("url"));
		properties.setProperty("maxActive", (String)p.handleGetObject("maxActive"));
		properties.setProperty("maxIdle", (String)p.handleGetObject("maxIdle"));
		properties.setProperty("maxWait", (String)p.handleGetObject("maxWait"));
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.repositories.Repository#setup()
	 */
	public void setup() throws RepositoryException {
		log.info("Creating Mysql repository");
		loadConfiguration();
		// Creates the repository data source
		try {
			repositoryDS = BasicDataSourceFactory.createDataSource(properties);
			log.info("Repository class created succesfuly");

			MysqlDataSourceLoader dsLoader = new MysqlDataSourceLoader(this);
			log.info("Loading application datasources");
			dataSources = dsLoader.getApplicationDataSources();
			log.info("Datasources loaded succesfuly");

		} catch (Exception ex){
			log.error("Error creating repository data source: " + ex.toString());
			throw new RepositoryException("Error creating repository data source: " + ex.toString());
		}
	}
	
	public DAOFactory getDaoFactory(){
		return new MysqlDAOFactory();
	}
	
	public ApplicationDataSource getApplicationDataSource(int idDataSource){
		return (ApplicationDataSource)dataSources.get("" + idDataSource);
	}
	
}
